/**
 * 
 */
package com.wskj.library.book.controller;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.wskj.library.pojo.BookCategory;
import com.wskj.library.pojo.BookInfo;
import com.wskj.library.service.BookService;
import com.wskj.library.service.impl.BookServiceImpl;
import com.wskj.util.RequestUtil;

/**
 * @author 胡洋
 * @describe 
 * @Date 2018年3月22日下午6:08:54
 * @version 1.0
 */
@MultipartConfig
@WebServlet("/book/add.do")
public class AddBookServlet extends HttpServlet {
	private BookService bookService=new BookServiceImpl();
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
	    List<BookCategory> categories=	bookService.queryAllCategory();
		
	    req.setAttribute("ca",categories);
		req.getRequestDispatcher("/WEB-INF/page/book/add.jsp").forward(req, resp);
	}
	
	
	//用户提交过来 ...	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		BookInfo bookInfo = RequestUtil.convertRequestToEntity(BookInfo.class, req);
		
		//获取文件 ..... type =file   对应  part
		Part part = req.getPart("book_img");
				//获取时用户上传文件的名称  
		String fileName = part.getSubmittedFileName();
		
		String ext=fileName.substring(fileName.lastIndexOf(".")+1);
		String newName=UUID.randomUUID().toString()+"."+ext;		
		//存储到本地磁盘的地址  ...
		part.write("D:/img/book/"+newName);
		//req.getParts();		
		String  imgPath="http://192.168.3.1:8080/img/book/"+newName;		
		bookInfo.setBimg(imgPath);		
		// 调用服务层 将 数据存储到数据库里面  .....			
	    @SuppressWarnings("unused")
		boolean result=	bookService.saveBookInfo(bookInfo);		
	    resp.sendRedirect(req.getContextPath()+"/book/list.do");
		
	}

}
